package com.thinktank.controller;

import static com.thinktank.util.DbUtil.*;

import java.io.*;
import java.sql.*;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.swing.JOptionPane;

import com.thinktank.dao.*;
import com.thinktank.vo.*;

public class CookieLoginController implements Controller {

	@Override
	public String execute(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		System.out.println("CookieLoginController");
		String email = null;
		String password = null;
		Member member = null;

		// 쿠키가 있을 때
		HttpSession session = request.getSession();
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			String no = null;
			for (int i = 0; i < cookies.length; i++)
				if (cookies[i].getName().equals("no"))
					no = cookies[i].getValue();
			if (no != null) {
				System.out.println("쿠키로그인");
				Connection con = getConnection();
				MemberDao dao = new MemberDao(con);
				member = dao.cookieLogin(no);
				close(con);
				if(member !=null){
					session.setAttribute("member", member);
					session.setAttribute("url", member.getmPage());
					return "redirect:home/home.do?p=1";
				}
			}
		}

		// post로 받을 때
		email = request.getParameter("email");
		password = request.getParameter("password");
		String cookie = request.getParameter("cookie");

		System.out.println("email : " + email);
		System.out.println("password : " + password);
		System.out.println("cookie : " + cookie);

		if (email != null && password != null) {
			Connection con = getConnection();
			MemberDao dao = new MemberDao(con);
			member = dao.login(email, password);
			close(con);
		}

		if (member != null) {
			System.out.println(member);
			// 쿠키에 MB_NO 추가
			if (cookie != null && cookie.equals("on")) {
				Cookie noCookie = new Cookie("no", ""+member.getmNo());
				noCookie.setMaxAge(60 * 60 * 24);
				response.addCookie(noCookie);
			}
			session.setAttribute("member", member);
			session.setAttribute("url", member.getmPage());
			return "redirect:home/home.do?p=1&url="+member.getmPage();
		} else {
			JOptionPane.showMessageDialog(null, "이메일 혹은 비밀번호가 일치하지 않습니다.");
			return "redirect:index/index.html";
		}

	}

}
